﻿var event = null;
var eventObj = null;
var borderColor = null;
var webServiceAddress = null;
var eventArray = null;
var roomCode = null;

$(document).ready(function () {

    webServiceAddress = $('#MainContent_serverPathHiddenField').val() + "schedulerWebService.asmx/";
    eventArray = new Array();
    roomCode = $('#MainContent_roomDropDownList option:selected').val();

    $('#editEventFS').hide();

    $('#calendar').fullCalendar({
        header: {
            left: 'prev,next today',
            center: 'title',
            right: 'month,agendaWeek,agendaDay'
        },
        defaultView: 'month',
        editable: true,

        events: function (start, end, callback) {
            eventArray = new Array();
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: webServiceAddress + "GetEventsForRoomInRange",
                data: "{ startDateRange: '" + NormalizeDateToString(start) + "', endDateRange: '" + NormalizeDateToString(end) + "', roomCode: '" + roomCode + "' }",
                dataType: "xml",
                async: false,
                success: function (data, textStatus, XMLHttpRequest) {
                    // Convert XML to JavaScript object
                    $(data).find("CalendarEvent").each(function () {
                        var event = new Object();

                        event.id = $(this).find("Id").text();
                        event.title = $(this).find("Title").text();
                        event.allDay = ($(this).find("AllDay").text() == "true") ? false : false;
                        event.start = $(this).find("Start").text();
                        event.end = $(this).find("End").text();
                        event.url = $(this).find("Url").text(); // Not needed.
                        event.className = $(this).find("ClassName").text();
                        event.editable = ($(this).find("Editable").text() == "true") ? true : false;
                        event.roomCode = $(this).find("RoomCode").text();

                        eventArray.push(event);
                    });
                    callback(eventArray);
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    alert(XMLHttpRequest + " Failure: " + textStatus + "->" + errorThrown);
                }
            });
        },

        eventDrop: function (event, delta) {
            SaveEventToDB(event);
        },

        loading: function (bool) {
            if (bool) $('#loading').show();
            else $('#loading').hide();
        },

        eventResize: function (event, dayDelta, minuteDelta, revertFunc) {
            SaveEventToDB(event);
        },

        eventClick: function (calEvent, jsEvent, view) {

            if (!calEvent.editable) return;
            // change the border color just for fun
            eventObj = this;
            borderColor = $(this).css('border-color');
            $(this).css('border-color', 'red');

            hideEventEdit(); // Clear previously clicked events.
            showEventEdit(calEvent);
        }

    });
});

function showEventEdit(e) {
    event = e;

    $('#editEventFS').show();
}

function hideEventEdit() {
    event = null;
    $(eventObj).css('border-color', borderColor);
    eventObj = null;
    borderColor = null;
    $('#editEventFS').hide();
    $('#calendar').fullCalendar('rerenderEvents');
}

function deleteEvent() {
    if (event != null) {
        $('#calendar').fullCalendar('removeEvents', event.id);
        event.title = '';
        SaveEventToDB(event);
        __doPostBack("MainContent_roomDropDownList", '');
    }
    hideEventEdit();
}
function endNowEvent() {
    if (event != null) {
        event.end = new Date();
        SaveEventToDB(event);
    }
    hideEventEdit();
}

function newEvent() {
    try {
        var event = new Object();

        event.id = -1;
        event.title = prompt("Enter meeting title", "Meeting");
        event.allDay = false;
        event.start = new Date(prompt("Enter Start Date/Time yyyy/M/dd HH:mm:ss", NormalizeDateToString(new Date())));
        event.end = new Date(event.start);
        event.end.setHours(event.end.getHours() + 1);
        event.end = new Date(prompt("Enter End Date/Time yyyy/M/dd HH:mm:ss", NormalizeDateToString(event.end)));
        event.url = ''; // Not needed.
        event.className = '';
        event.editable = true;
        event.roomCode = roomCode;

        if (!IsRoomReserved(event)) {
            SaveEventToDB(event);
            alert("Reservation Added!");
            __doPostBack("MainContent_roomDropDownList", '');
        }
        else {
            alert("Reservation not added, room is occupied!");
        }

    } catch (e) {
        alert("Reservation Failed!");
    }
}

function IsRoomReserved(event) {
    if (eventArray == null) return false;

    var ret = false;
    
    for(var i = 0; i < eventArray.length; i++) {
        var e = eventArray[i];
        
        if(e == null) continue;
        
        if (e.start != null && e.end != null) {
            var startsDuring = (e.start >= event.start && e.start <= event.end);
            var endsDuring = (e.end >= event.start && e.end <= event.end);

            if (startsDuring || endsDuring) {
                ret = true;
                break;
            }
        }
    }

    return ret;
}